package cn.kgc.crowdfundingadminspringboot.controller;

import cn.kgc.crowdfundingadminspringboot.common.ResultEntity;
import cn.kgc.crowdfundingadminspringboot.pojo.Menu;
import cn.kgc.crowdfundingadminspringboot.service.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/menu")
public class MenuController {

    @Resource
    MenuService menuService;

    @ResponseBody
    @RequestMapping("/get/whole/tree")
    public ResultEntity<Menu> getWholeTree(){
// 1.查询所有的树形节点用于组装
        List<Menu> menuList = menuService.getAll();
        // 2.将List<Menu>转换为Map<Menu的id,Menu>
        Map<Integer,Menu> menuMap = new HashMap<>();
        for (Menu menu : menuList) {
            menuMap.put(menu.getId(),menu);
        }

        // 3.声明变量用于存储根节点对象
        Menu rootNode = null;

        for (Menu menu : menuList) {
            //是父节点
            if (menu.getPid()==null){
                rootNode=menu;
                continue;
            }
            //是子节点从menuMap找到父节点，并添加到父节点的子节点集合中
            menuMap.get(menu.getPid()).getChildren().add(menu);
        }
        return ResultEntity.successWithoutData(rootNode);
    }

    @RequestMapping("/to/page.html")
    public String toPage(){
        return "menu-page";
    }

    @RequestMapping("/save")
    @ResponseBody
    public ResultEntity<String> saveMenu(Menu menu) {

        menuService.saveMenu(menu);

        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/get/{menuId}")
    @ResponseBody
    public ResultEntity<Menu> getMenuById(@PathVariable("menuId") Integer menuId) {

        Menu menu = menuService.getMenuById(menuId);

        return ResultEntity.successWithoutData(menu);
    }


    @RequestMapping("/update")
    @ResponseBody
    public ResultEntity<String> update(Menu menu){
        menuService.update(menu);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ResultEntity<String> delete(Integer id){
       menuService.delete(id);
        return ResultEntity.successWithoutData();
    }
}




